﻿using Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Reflection;

namespace CKS.Schedule
{
    public class TaskSchedulerServer
    {
       public static ServiceProvider ServiceProvider = null;

        public static void RegisterService()
        {
            var assembly = Assembly.GetExecutingAssembly();
            var jobs = assembly.GetTypes().Where(a => a.GetCustomAttribute<ScheduleAttribute>() != null).ToArray();

            ServiceCollection collection = new ServiceCollection();
            foreach (var job in jobs)
            {
                IHostedService service = (IHostedService)Activator.CreateInstance(job);

                collection.AddSingleton(job, service);
            }

            ServiceProvider = collection.BuildServiceProvider();
            InternalApp.JobProvider = ServiceProvider;
        }

        public static void Start()
        {

           
           
            var assembly = Assembly.GetExecutingAssembly();
            var jobtypes = assembly.GetTypes().Where(a => a.GetCustomAttribute<ScheduleAttribute>() != null).ToArray();

            //var jobs2 = InternalApp.ServiceProvider.
            Parallel.ForEach(jobtypes, (tp) =>
            {
                
               var job = ServiceProvider.GetService(tp) as CronJobBase;
               if(job != null)
                  job.StartAsync(CancellationToken.None);

            });

        }


    }
}
